<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="filelist"
      :limit="1"
      :class="{disabled:filelistcount}"
      :on-change="handleChange"
      :before-upload="beforeupload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
    <el-progress
      v-if="showPercent"
      :percentage="percent"
      style="width:250px"
      class="progress"
    />
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云的包
// 需要实例化
const cos = new COS({
  SecretId: 'AKID231qRnulNkriKhphkeJkwsY0DCwSknbA',
  SecretKey: 'PbYFhusa3IH0VlmbBXeW9XgZDcmhNo1y'
}) // 实例化的包 已经具有了上传的能力 可以上传到该账号里面的存储桶了
export default {
  name: 'Uploadimage',
  components: {
  },
  props: {
    value: {
      type: [String],
      default: ''
    }
  },
  data() {
    return {
      percent: 0,
      showPercent: false,
      dialogImageUrl: '',
      dialogVisible: false,
      filelist: [

      ], // 照片显示根据这个显示
      uid: null,
      imgurl: ''
    }
  },
  computed: {
    filelistcount() {
      return this.filelist.length === 1
    }
  },
  watch: {
    value(n, o) {
      // console.log(n)
      // console.log(o)
      if (n !== o) {
        if (this.value) {
          this.filelist = [{ url: this.value, upload: true }]
        }
      }
      if (n === o) {
        // console.log(1)
        // if (this.value) {
        //   this.filelist = [{ url: this.value, upload: true }]
        // }
      }
    }

  },
  mounted() {
    if (this.value) {
      this.filelist = [{ url: this.value, upload: true }]
    }
    // console.log(this.value)
  },
  created() {
    // console.log(1)
  },
  methods: {
    handleRemove(file, fileList) {
      this.filelist = fileList
      this.$emit('input', '')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) { // 这个函数会执行两次 1.添加文件2.上传失败
      this.filelist = [...fileList]
    },
    beforeupload(file) {
      this.showPercent = true
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      const maxsize = 5 * 1024 * 1024
      // console.log(file)
      if (!types.some((item) => item === file.type)) {
        this.$message.error('文件类型不对')
        return false
      }
      if (file.size > maxsize) {
        this.$message.error('文件超过5M')
        return false
      }
      this.uid = file.uid
      return true
    },
    upload(params) {
      cos.putObject({
        Bucket: 'wangrui-1312621362', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        this.filelist = this.filelist.map((item) => {
          if (item.uid === this.uid) {
            item.url = `https://${data.Location}`
            // this.imgurl = item.url
            this.$emit('input', item.url)
            item.upload = true
          }
          this.$message.success('上传成功')
          return item
        })
        setTimeout(() => {
          this.showPercent = false // 隐藏进度条
          this.percent = 0 // 进度归0
        }, 1000)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.disabled .el-upload--picture-card {
  display: none;
}
.el-upload--picture-card{
  position: relative;
}
.el-icon-plus{
  position: absolute;
  left: 35px;
  top: 12px;
}
.el-upload-list__item {
  left: 100px;
}
// ::v-deep .el-upload-list__item {
//   width: 100px;;
// }
.el-upload-list--picture-card .el-upload-list__item{
  width: 200px;
  height: 100px;
}
.progress{
  left: 100px;
}

</style>
